from datetime import datetime

from django import forms
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.utils.translation import ugettext_lazy as _

from popboard.models import Category, ForumProfile, Thread, Post

class PostForm(forms.Form):
    body = forms.CharField(widget=forms.Textarea)
    thread = forms.ModelChoiceField(queryset=Thread.objects.all(), widget=forms.HiddenInput)
    
    def clean_thread(self):
        if self.cleaned_data["thread"].closed:
            raise forms.ValidationError(_("Thread Closed"))
        return self.cleaned_data["thread"] 
        
    def save_with_user(self, user, ip_address):
        thread = self.cleaned_data['thread']
        post = Post.objects.create(body_raw=self.cleaned_data['body'], 
                                    ip=ip_address, 
                                    thread=thread, 
                                    user=user, 
                                    site=Site.objects.get_current())
        thread.last_post = post
        thread.modified = datetime.now()
        thread.save()
        return post
        
class ForumProfileForm(forms.ModelForm):
    def __init__(self, user, *args, **kwargs):
        self.user = user
        super(ForumProfileForm, self).__init__(*args, **kwargs)
        
    def save(self):
        self.cleaned_data["user"] = self.user
        return super(ForumProfileForm, self).save()
        
    class Meta:
        model = ForumProfile
        exclude = ('user',)

class ThreadForm(forms.Form):
    title = forms.CharField(max_length=255)
    body = forms.CharField(widget=forms.Textarea)
    
    def __init__(self, is_moderator=False, *args, **kwargs):
        super(ThreadForm, self).__init__(*args, **kwargs)
        if is_moderator:
            self.fields['sticky'] = forms.BooleanField(_("Sticky"))

    def save_with_user(self, user, ip_address, category):
        site = Site.objects.get_current()
        thread = Thread.objects.create(title=self.cleaned_data['title'],
                                        user=user, 
                                        category=category, 
                                        site=site)
                                        
        post = Post.objects.create(body_raw=self.cleaned_data['body'], 
                                    ip=ip_address, 
                                    thread=thread, 
                                    user=user, 
                                    site=site)
        if 'sticky' in self.cleaned_data:
            thread.sticky = self.cleaned_data['sticky']
            
        thread.first_post = post
        thread.last_post = post
        thread.modified = datetime.now()
        thread.save()
        return thread
        
        